<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.name" placeholder="姓名" class="handle-input mr10" style="width: 8%"></el-input>
                <el-input v-model="query.sex" placeholder="性别" class="handle-input mr10" style="width: 8%"></el-input>
                <el-date-picker v-model="query.workyear" placeholder="首次工作年份" type="datetime" value-format="yyyy-MM" format="yyyy-MM" class="handle-input mr10" style="width: 8%"></el-date-picker>
                <el-input v-model="query.skill" placeholder="技能" class="handle-input mr10" style="width: 8%"></el-input>
                <el-input v-model="query.region" placeholder="地域" class="handle-input mr10" style="width: 8%"></el-input>
                <el-input v-model="query.education" placeholder="学历" class="handle-input mr10" style="width: 8%"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-circle-plus-outline" class="handle-del floatr" @click="addSysRole">新增</el-button>
                <el-button type="primary" icon="el-icon-download" class="handle-del floatr" @click="batch_export">导出</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" label="序号" width="55" align="center" ></el-table-column>
                <el-table-column prop="name" label="姓名"></el-table-column>
                <el-table-column prop="sex" label="性别"></el-table-column>
                <el-table-column prop="region" label="地域"></el-table-column>
                <el-table-column prop="skill" label="技能"></el-table-column>
                <el-table-column prop="workyear" label="首次工作年份">
                  <template slot-scope="scope">{{scope.row.workyear| dateFormat}}</template>
                </el-table-column>
                <el-table-column prop="education" label="学历"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-edit-outline"
                            @click="handleSelect(scope.$index, scope.row)"
                        >详情</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-download"
                            @click="downloadSelect(scope.$index, scope.row)"
                        >下载简历</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <el-image-viewer v-if="previewFlg" :url-list="[previewSrc]"  :on-close="closeViewer"/>
        <!-- 编辑弹出框 -->
        <el-dialog :title="editstatus=='add'?'新增':editstatus=='update'?'编辑':'详情'" :close-on-click-modal="false" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="姓名" label-width="40%" prop="name" >
                      <el-input maxlength="20" v-model="form.name" ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="性别" label-width="40%" prop="sex">
                      <el-input maxlength="20" v-model="form.sex" ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="出生日期" label-width="40%" prop="borndate" >
                    <el-date-picker v-model="form.borndate" type="datetime" value-format="yyyy-MM-dd"  format="yyyy-MM-dd" style="width: 100%"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="身份证号" label-width="40%" prop="idnum" >
                    <el-input maxlength="20" v-model="form.idnum" ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="首次工作年份" label-width="40%" prop="workyear" >
                    <el-date-picker v-model="form.workyear" type="datetime" value-format="yyyy-MM"  format="yyyy-MM" style="width: 100%"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="联系方式" label-width="40%" prop="tel" >
                    <el-input maxlength="20" v-model="form.tel" ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                 <el-col :span="10">
                   <el-form-item label="学历" label-width="40%" prop="education" >
                     <el-input maxlength="20" v-model="form.education" ></el-input>
                   </el-form-item>
                 </el-col>
                 <el-col :span="10">
                   <el-form-item label="技能" label-width="40%" prop="skill" >
                     <el-input maxlength="20" v-model="form.skill" ></el-input>
                   </el-form-item>
                 </el-col>
              </el-row>
              <el-row>
                 <el-col :span="10">
                   <el-form-item label="地域" label-width="40%" prop="region" >
                     <el-input maxlength="20" v-model="form.region" ></el-input>
                   </el-form-item>
                 </el-col>
                 <el-col :span="10">
                   <el-form-item label="录入人" label-width="40%" prop="enter" >
                     <el-select v-model="form.enter" placeholder="请输入关键词" class="interval" @change="handleSelectChange($event)" clearable filterable remote style="width: 100%">
                       <el-option value="">请选择</el-option>
                       <el-option
                           v-for="item in restaurants"
                           :key="item.id"
                           :label="item.account"
                           :value="item">
                       </el-option>
                     </el-select>
                   </el-form-item>
                 </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="录入时间" label-width="40%" prop="addtime" >
                    <el-date-picker v-model="form.addtime" type="datetime" value-format="yyyy-MM-dd"  format="yyyy-MM-dd" style="width: 100%"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="20">
                  <el-form-item label="备注" label-width="20%"  prop="remarks" >
                    <el-input type="textarea" rows="5" v-model="form.remarks" maxlength="200"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="简历链接" label-width="40%" prop="link" >
                    <el-upload  style="display:inline-block;"
                                class="avatar-uploader"
                                ref="uploadImage"
                                action=""
                                multiple
                                :auto-upload="false"
                                :show-file-list="false"
                                accept=""
                                :http-request="uploadImg"
                                :on-change="imgSaveToUrl">
                      <el-button style="background-color:#F95714;border-radius:4px;width:220px;height:40px;color:#fff" >上传简历</el-button>
                    </el-upload>
                    <div style="display:inline-block;height:70px;overflow:hidden;vertical-align:top;color:red;margin-left: 10px">
                      {{form.linkName}}
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer" v-if="editstatus !='select'">
                <el-button @click="butCancel">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')" v-preventReClick>确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { selectPage,addResume,updateResume,delResume,getResumeByID} from '../../api/resume';
    import { selectAll} from '../../api/sysUser';
    import { getDictionarys} from '../../api/dictionary';
    import { _dateFormat} from '../../utils/tool';
    import { exportMethod} from '../../utils/util';
    import { isvalidPhone,isvalidEmail,isvalidIdnum} from '../../utils/validate';
    import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
    var checkphone = (rule, value, callback) => {
        if (!value) {
            callback(new Error("请输入手机号"));
        } else if (!isvalidPhone(value)) {//引入methods中封装的检查手机格式的方法
            callback(new Error("请输入正确的手机号!"));
        } else {
            callback();
        }
    };
    var checkEmail = (rule, value, callback) => {
        if (!isvalidEmail(value)) {
            callback(new Error("请输入正确的邮箱!"));
        } else {
            callback();
        }
    };
    let app ;
    export default {
        name: 'device',
        components: { ElImageViewer },
        data() {
            return {
                query: {
                    name:"",
                    tel:"",
                    status:'',
                    category:1,
                    enter:localStorage.getItem('ms_username'),
                    enterrole:localStorage.getItem('ms_userrole'),
                    pageIndex: 1,
                    pageSize: 10
                },
                //文件上传
                fileHeaders: {
                    'X-Token': localStorage.getItem("X-Token")
                },
                enterrole:localStorage.getItem('ms_userrole'),
                previewFlg:false,
                previewSrc: '',
                tableData: [],
                multipleSelection: [],
                sexList:[],
                positionList:[],
                positionQueryList:[],
                invoiceList:[],
                provinceList:[],
                contractList:[],
                contractQueryList:[],
                cityList:[],
                areaList:[],
                editVisible: false,
                addVisible: false,
                editstatus:"",
                pageTotal: 0,
                restaurants: [],
                form: {
                    name:"",
                    mobile:"",
                    sex:"",
                    age:"",
                    borndate:"",
                    recommender:"",
                    email:"",
                    address:"",
                    quittime:"",
                    paydate:"",
                    linkName:"",
                    link:""
                },
                paydate: {
                  disabledDate: time => {
                    return time.getTime() < new Date(this.form.worktime).getTime();
                  }
                },
                quittime: {
                  disabledDate: time => {
                    return time.getTime() < new Date(this.form.worktime).getTime();
                  }
                },
                userList:[],
                rules:{
                    name :[{required: true, message: '姓名不能为空', trigger: 'blur'}],
                    sex :[{required: true, message: '性别不能为空', trigger: 'blur'}],
                    borndate :[{required: true, message: '出生日期不能为空', trigger: 'blur'}],
                    workyear :[{required: true, message: '工作年份不能为空', trigger: 'blur'}],
                    tel :[{required: true, message: '联系方式不能为空', trigger: 'blur'}],
                    partner :[{required: true, message: '合作商名称不能为空', trigger: 'blur'}],
                    contract :[{required: true, message: '合作性质不能为空', trigger: 'blur'}],
                    salary :[{required: true, message: '薪资不能为空', trigger: 'blur'}],
                    price :[{required: true, message: '单价不能为空', trigger: 'blur'}],
                    paydate :[{required: true, message: '首次回款日期不能为空', trigger: 'blur'}],
                    technology :[{required: true, message: '技能不能为空', trigger: 'blur'}],
                    state :[{required: true, message: '状态（在职/离职）不能为空', trigger: 'blur'}],
                    mobile :[{required: true, validator: checkphone, trigger: 'blur'}],
                    email:[{required: false, validator: checkEmail, trigger: 'blur'}],
                },
                idx: -1,
                id: -1,
            };
        },
        created() {
            var query=this.$route.query;
            if(query.name == "staff1"){
              this.query.category = 1;
            }else if(query.name == "staff2"){
              this.query.category = 2;
            }else if(query.name == "staff3"){
              this.query.category = 3;
            }else if(query.name == "staff4"){
              this.query.category = 4;
            }
            this.getData();
        },
        filters:{
            //格式化后台传过来的时间戳
            dateFormat(time) {
                if(time == "" || time == null ){
                    return ""
                }
                let date = new Date(time);
                return _dateFormat(date,'yyyy-MM-dd')
            },
        },
        mounted(r) {
          var that = this;
          selectAll({}).then(res => {
            var restaurants = [];
            for(var key in res){
                restaurants.push(res[key]);
            }
            that.restaurants = restaurants;
          });
        },
        watch: {
        },
        methods: {
          contractFormat(row, column){
              for(var key in this.contractList){
                if(this.contractList[key].code == row.contract){
                  return this.contractList[key].value
                }
              }
              return ""
            },
            statusFormat(row, column){
              for(var key in this.positionList){
                if(this.positionList[key].code == row.state){
                  return this.positionList[key].value
                }
              }
              return "";
            },
            querySearch(queryString, cb) {
              var restaurants = this.restaurants;
              var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
              cb(results);
            },
            createFilter(queryString) {
              return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);//字符串头查询
              };
            },
            loadAll() {
              return  this.userList;
            },
            // 获取list
            getData() {
                selectPage(this.query).then(res => {
                    this.tableData = res.items;
                    this.pageTotal = res.total;
                });
                this.getDictionarys();
            },
            // 查询字典表
            getDictionarys(){
                // 获取性别
                getDictionarys("SEX").then(res => {
                    this.sexList = res;
                });
              getDictionarys("POSITION").then(res => {
                this.positionList = res;
                this.positionQueryList = JSON.parse(JSON.stringify(res));
                this.positionQueryList.unshift({value:"全部",code:""})
              });
              getDictionarys("INVOICE").then(res => {
                this.invoiceList = res;
              });
              getDictionarys("CONTRACT").then(res => {
                this.contractList = res;
                this.contractQueryList = JSON.parse(JSON.stringify(res));
                this.contractQueryList.unshift({value:"全部",code:""})
              });
            },
            // 查询分组
            getDicGroup(id){
                var _that =this;
                if(id != "" && id != null){
                    getResumeByID(id).then(res => {
                    _that.form = res;
                    });
                }
            },
                // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                var param ={};
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    param.id = row.id ;
                    delResume(param).then(res => {
                        this.$message.success('删除成功');
                        this.getData();
                    });
                })
                    .catch(() => {});
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = [];
                for (let i = 0; i < val.length; i++) {
                    if (this.multipleSelection.indexOf(val[i].id) === -1) {
                        this.multipleSelection.push(val[i].id)
                    }
                }
            },
            // 编辑操作
            handleEdit(index, row) {
                this.form.link = "";
                this.form.linkName = "";
                this.editstatus ="update";
                this.idx = index;
                this.editVisible = true;
                this.getDicGroup(row.id);
            },
            // 查看
            handleSelect(index, row) {
              this.editstatus ="select";
              this.idx = index;
              this.editVisible = true;
              this.getDicGroup(row.id);
            },
            //新增操作
            addSysRole() {
              this.editstatus ="add";
              Object.keys(this.form).forEach(key => (this.form[key] = ''));
              this.form.link = "";
              this.form.linkName = "";
              this.editVisible = true;
              this.form.enter = localStorage.getItem('ms_username');
              this.form.enterId = localStorage.getItem('ms_userid');
              this.getDicGroup();
            },
            handleSelectChange(param){
              this.form.enterId = param.id;
              this.form.enter = param.account;
              this.$forceUpdate()
            },

            // 保存编辑
            saveEdit(formData) {
               var that = this;
                this.form.category =this.query.category
                this.$refs[formData].validate((valid) => {
                    if (valid) {
                      that.$refs.uploadImage.submit() //必须使用此方法才会触发自定义上传方法以获取文件对象
                      var fileForm = new FormData() //携带文件必须使用此对象
                      if (that.form.link) {
                        fileForm.append("file", that.form.link)
                      }
                      fileForm.append("dto", JSON.stringify(this.form))
                      if(this.form.id != null && this.form.id != undefined && this.form.id != ""){
                            // 编辑
                            updateResume(fileForm).then(res => {
                                this.$message.success("编辑成功");
                                this.getData();
                                this.butCancel();
                            }) .catch((res) => {
                                this.$message.error(res.errorMsg);
                            });
                        }else{
                            // 新增
                            addResume(fileForm).then(res => {
                                this.$message.success("新增成功");
                                this.getData();
                                this.butCancel();
                            }).catch((res) => {
                                this.$message.error(res.errorMsg);
                            });
                        }
                    }
                })
            },
            butCancel(){
                this.$refs.uploadImage.clearFiles(); // 清空建立
                this.editVisible = false;
                this.addVisible = false;
                Object.keys(this.form).forEach(key => (this.form[key] = ''));
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            // 导出
            batch_export(){
                var that = this;
                let myObj = {
                    method: 'get',
                    url: '/rest/staff1/exportMember',
                    fileName: '会员统计',
                    params:  `name=`+that.query.name+`&mobile=`+that.query.tel+`&enter=`+localStorage.getItem('ms_username')
                }
                exportMethod(myObj)
            },
            checkIdnum (rule, value, callback){
              if (!value) {
                callback(new Error("请输入身份证"));
              } else if(!isvalidIdnum(value)) {
                callback(new Error("请输入正确的身份证!"));
              } else {
                //this.go(value.length);
                callback();
              }
            },
            // 实现自动生成生日，性别，年龄
            go(val) {
              let iden = this.form.idnum;
              let birth = null;
              let myDate = new Date();
              let month = myDate.getMonth() + 1;
              let day = myDate.getDate();
              let age = 0;
              if(val===18){
                age = myDate.getFullYear() - iden.substring(6, 10) - 1;
                birth = iden.substring(6,10)+"-"+iden.substring(10,12)+"-"+iden.substring(12,14);
                if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;
              }
              if(val===15){
                age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
                birth = "19"+iden.substring(6,8)+"-"+iden.substring(8,10)+"-"+iden.substring(10,12);
                if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
              }
              this.form.age = age;
              this.form.borndate = birth;
            },
            uploadImg (param) {
              this.form.link = param.file
            },
            // 上传
            imgSaveToUrl(event) {
              this.form.linkName = event.name;
            },
            // 下载
            downloadSelect(index, row){
              if(row.link == ''){
                this.$message({
                  message: '没有源文件',
                  type: 'warning'
                })
              }else{
                // 创建a标签
                let link = document.createElement('a')
                // href链接
                link.setAttribute('href', this.$imgUrl+row.link +"&name="+row.linkName)
                // 自执行点击事件
                link.click()
              }
            },
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .mr10 {
        margin-right: 10px;
    }
    .floatr {
        float: right;
    }
</style>